import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import store from "@/store";
import axios from 'axios';


const routes: Array<RouteRecordRaw> = [
    {
        path: '/',
        name: 'home',
        component: () => import('../views/HomeIndex.vue')
    },
    {
        path: '/signup',
        name: 'signup',
        component: () => import('../views/SignUp.vue'),
        meta: { redirectAlredyLogin: true }
    },
    {
        path: '/login',
        name: 'login',
        component: () => import('../views/LoginIndex.vue'),
        meta: { redirectAlredyLogin: true }
    },
    {
        path: '/column/:id',
        name: 'column',
        component: () => import('../views/ColumnDetail.vue'),

        meta: { requiredLogin: true }
    },
    {
        path: '/create',
        name: 'create',
        component: () => import('../components/CreatePost.vue'),
        // 在创建文章时，如果没有登录，就跳转到登录
        meta: { requiredLogin: true }
    },
    {
        path: '/post/:id',
        name: 'post',
        component: () => import('../views/PostDetail.vue'),
        // 在创建文章时，如果没有登录，就跳转到登录
        meta: { requiredLogin: true }
    }
]

const router = createRouter({
    history: createWebHistory(process.env.BASE_URL),
    routes
})
// router.beforeEach((to, from, next) => {
//     if (to.name !== 'login' && !store.state.user.isLogin) {
//         next({ name: 'login' })
//     } else {
//         next()
//     }
// })
// 通过路由元信息
// router.beforeEach((to, from, next) => {
//     // console.log(to.meta);
//     if (to.meta.requiredLogin && !store.state.user.isLogin) {
//         next({name: 'login'})
//     } else if (to.meta.redirectAlredyLogin && store.state.user.isLogin) {
//         next('/')
//     } else {
//         next()
//     }
// })
router.beforeEach((to, from, next) => {
    const { token, user } = store.state
    const { redirectAlredyLogin, requiredLogin } = to.meta
    if (user.isLogin) {
        if (redirectAlredyLogin) {
            next('/')
        } else {
            next()
        }
    } else {
        if (token) {
            axios.defaults.headers.common.Authorization = `Bearer ${token}`
            store.dispatch('fetchCurrentUser').then(() => {
                // 判断是否在登录位置
                if (redirectAlredyLogin) {
                    next('/')
                } else {
                    next()
                }
            }).catch(() => {
                store.commit('logout')
                next('/login')
            })

        } else {
            if (requiredLogin) {
                next('/login')
            } else {
                next()
            }
        }
    }
})
export default router
